from django.conf import settings
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from haystack.views import SearchView

from apps.contents.models import GoodsCategory
from apps.goods.models import SKU
from .utils import get_breadcrumb



class GoodListView(View):

    def get(self, request, category_id):

        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')

        if not all([category_id, page, page_size, ordering]):
            return JsonResponse({'code': 200, 'errmsg': '缺少必传参数'})

        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 200, 'errmsg': '查询分类不存在'})

        breadcrumb = get_breadcrumb(category)

        # 排序方式:
        try:
            skus = SKU.objects.filter(category=category,
                                      is_launched=True).order_by(ordering)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取mysql数据出错'})

        paginator = Paginator(skus, 5)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page)
        except EmptyPage:
            # 如果page_num不正确，默认给用户400
            return JsonResponse({'code': 400,
                                 'errmsg': 'page数据出错'})
        # 获取列表页总页数
        total_page = paginator.num_pages

        # 定义列表:
        list = []
        # 整理格式:
        for sku in page_skus:
            list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        # 把数据变为 json 发送给前端
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'breadcrumb': breadcrumb,  # 面包屑导航
            'list': list,
            'count': total_page
        })


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行 JSON 数据"""
        # 根据销量倒序
        try:
            skus = SKU.objects.filter(category_id=category_id,
                                  is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取商品出错'})
        # 转换格式:
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image.url,
                'name':sku.name,
                'price':sku.price
            })

        return JsonResponse({'code':0,
                             'errmsg':'OK',
                             'hot_skus':hot_skus})



class MySearchView(SearchView):
    """自定义商品搜索视图
    目的：为了重写create_response(),并返回检索后的JSON数据
    GET /search/
    """

    @property
    def results_per_page(self):
        if int(self.request.GET.get('page_size')):
            return int(self.request.GET.get('page_size'))

        return super().results_per_page



    def create_response(self):
        """返回检索后的JSON数据"""
        # 获取检索到的数据
        context = self.get_context()

        # 获取检索到的模型数据
        results = context['page'].object_list

        # 遍历results，取出检索到的SKU，再转字典列表
        data_list = []
        for result in results:
            data_list.append({
                'id': result.object.id,
                'name':result.object.name,
                'price':result.object.price,
                'default_image_url':result.object.default_image.url,
                'searchkey':context.get('query'),
                # 'page_size': context['page'].paginator.num_pages,
                'page_size':self.results_per_page,
                'count':context['page'].paginator.count
            })

        # 将检索到数据转成JSON返回即可
        return JsonResponse(data_list, safe=False)
